<?php

class utilitiesController extends controllerBase {
	protected $mode = AETHER_CLI;
	protected $view = false;
	protected $helpers = array();
	protected $models = array();
	protected $beforeFilters = array();
	protected $beforeAfter = array();
	
	function generateHtaccess() {
		if(!$fh = fopen('.htaccess', 'w')) {
			echo 'Could not open ".htaccess". Attempting a temporary file, ".htaccess.tmp".  Move to ".htaccess" when completed.';  
			if(!$fh = fopen('.htaccess.tmp', 'w')) {
				die('Could not create/open ".htaccess.tmp"');
			}
		}

		$content = '<IfModule mod_rewrite.c>'.NL;
		$domain = $this->aether->config->get('general', 'domain');
		$webRoot = $this->aether->config->get('general', 'webRoot');
		$domain = str_replace('http://www.','',$domain);
		$domain = str_replace('.','\.',$domain);
		$args = $this->getParam('args');
		if(isset($args['n'])) {
			$content .= NL.
				TAB.'RewriteCond %{HTTP_HOST} .'.NL.
				TAB.'RewriteCond %{HTTP_HOST} !^'.$domain.NL.
				TAB.'RewriteRule (.*) http://'.$domain.'/$1 [R=301,L]'.NL;
		} else if(isset($args['w'])) {
			$content .= NL.
				TAB.'RewriteCond %{HTTP_HOST} ^'.$domain.' [NC]'.NL.
				TAB.'RewriteRule ^(.*)$ http://www.'.$domain.'/$1 [L,R=301]'.NL; 
		}

		$content .= NL.
			TAB.'Options +FollowSymlinks'.NL.
			TAB.'RewriteEngine On'.NL.
			TAB.'RewriteRule ^images(.*)$ app/images$1 [L]'.NL.
    			TAB.'RewriteCond %{REQUEST_FILENAME} !-f'.NL.
    			TAB.'RewriteRule ^(.*)$ index.php/$1 [QSA,L]'.NL.
			TAB.'RedirectMatch 403 \.hg/|\.svn/|\.git/|\.bzr/'.NL.
		NL.'</IfModule>'.NL.NL;
		fwrite($fh, $content);
		fclose($fh);
		echo 'Success!';
	}
	
	function updateCrontab() {
		$appName = $this->aether->config->get('general','appNameFriend');
		if(!$crontab = file_get_contents('/etc/crontab')) {
			die('Could not open crontab for reading.  (Are you root?)');
		}
		
		$regexName = str_replace('-','\-',$appName);
		$crontab = preg_replace('/#startAetherCron\-'.$regexName.'.*?#endAetherCron\-'.$regexName.'/s', '', $crontab);

		$crontab .= NL.'#startAetherCron-'.$appName.NL;
		require('app/controllers/cronController.php');
		$controller = new cronController($this->aether);
		$methods = get_class_methods($controller);
		$aetherDir = $this->aether->config->get('general', 'systemRoot');
		foreach($methods as $method) {
			if($method!='__construct'&&$method!='flash') {
				$settings = $controller->$method;
				$crontab .= $settings['minute'].' '.$settings['hour'].' '.$settings['dayOfMonth'].' '.$settings['month'].' '.$settings['dayOfWeek'].' root ';
				if(isset($settings['command'])) {
					$crontab .= str_replace('[aetherDir]', $aetherDir, $settings['command']);
				} else {
					$crontab .= $aetherDir.'cli.php cron '.$method;
				}
				$crontab .= NL;
			}
		}
		$crontab .= '#endAetherCron-'.$appName.NL;
		if(!$fh = fopen('/etc/crontab', 'w')) {
			die('Could not open crontab for writing.  (Are you root?)');
		}
		fwrite($fh, $crontab);
		fclose($fh);
		echo 'Success!';
	}
}

?>
